from flask import Blueprint,request,jsonify
import json
from dat import db

bp_wenz=Blueprint('wenz',__name__)

@bp_wenz.route('/wenz',methods=['POST','GET'])
def wenz():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        print(data)
        sql = '''insert into wenz values (%d,"%s","%s")''' %(0,data['name'],data['content'])
        db.insert(sql)
        return jsonify({"code":200})
    elif request.method == 'GET':
        sql ='select * from wenz'
        res = db.findall(sql)
        return jsonify({'code':200,'list':res})


@bp_wenz.route('/user',methods=['POST','GET'])
def user():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        print(data['username'])
        sql = '''insert into wuser values (%d,"%s","%s")''' %(0,data['username'],data['password'])
        db.insert(sql)
        return jsonify({'code':200})

@bp_wenz.route('/login',methods=['POST'])
def login():
    if request.method== 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = """select * from wuser where username = "%s" """%(data['username'])
        res = db.findone(sql)
        if res:
            if res['password'] == data['password']:
                return jsonify({'code':200,'wenid':res['id']})
            else:
                return jsonify({'code':20010,'mes':'密码错误'})
        else:
            return jsonify({"code":20011,'mes':'用户名不存在'})

@bp_wenz.route('/com',methods=['POST','GET'])
def com():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = """insert into com values (%d,%d,%d,"%s")"""%(0,int(data['uid']),int(data['wid']),data['comment'])
        db.insert(sql)
        return jsonify({'code':200})
    elif request.method == 'GET':
        sql = '''select * from com'''
        res = db.findall(sql)
        return jsonify({'code':200,'list':res})